package com.sx.manage.controller.company;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sx.common.util.NumberUtil;
import com.sx.common.util.StringUtil;
import com.sx.common.util.ValidateUtil;
import com.sx.common.util.http.constants.PaperType;
import com.sx.manage.biz.company.IMCompanyBiz;
import com.sx.manage.controller.base.MBaseController;
import com.sx.manage.service.bank.IMBaseConsumerBankMapService;
import com.sx.manage.service.company.IMBaseCompanyService;
import com.sx.manage.service.company.MCompanyWebServiceImpl;
import com.sx.manage.service.company.type.change.MCompanyTypeChangeWebServiceImpl;
import com.sx.manage.service.sys.IMBaseSystemConfigInfoService;
import com.sx.manage.servlet.ViewAndModel;
import com.sx.model.manage.mybatis.form.bank.MConsumerBankMapForm;
import com.sx.model.manage.mybatis.form.consumer.MCompanyForm;
import com.sx.model.manage.mybatis.vo.bank.MDropDownVO;
import com.sx.model.manage.mybatis.vo.company.MCompanyVO;
import com.sx.model.manage.mybatis.vo.consumer.MConsumerBankMapVO;
import com.sx.model.manage.mybatis.vo.consumer.MVerifOpenAccountVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.result.ResultDropDownListVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;
import com.sx.model.manage.mybatis.vo.result.ResultObjectVO;
import com.sx.model.manage.mybatis.vo.result.ResultVerifyVO;

/**
 * 公司管理
 * 
 * @author zwm
 *
 */
@Controller
@RequestMapping("/company")
public class MCompanyController extends MBaseController {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Resource(name = "mCompanyBizImpl")
	private IMCompanyBiz mCompanyBizImpl;

	@Resource(name = "mBaseCompanyServiceImpl")
	private IMBaseCompanyService mBaseCompanyServiceImpl;

	@Resource(name = "companyWebServiceImpl")
	private MCompanyWebServiceImpl companyWebServiceImpl;

	@Resource(name = "companyTypeChangeWebServiceImpl")
	private MCompanyTypeChangeWebServiceImpl companyTypeChangeWebServiceImpl;
	// 系统参数配置
	@Resource(name = "mBaseSystemConfigInfoServiceImpl")
	private IMBaseSystemConfigInfoService mBaseSystemConfigInfoServiceImpl;
	
	// 用户银行关系
	@Resource(name = "mBaseConsumerBankMapServiceImpl")
	private IMBaseConsumerBankMapService mBaseConsumerBankMapServiceImpl;
	
	@RequestMapping(value = "query_code")
	@ResponseBody
	public ViewAndModel add_viewCompany() {
		return companyWebServiceImpl.add_viewCompany(this.createView());
	}

	/**
	 * 添加公司数据信息
	 * 
	 * @param request
	 * @param response
	 * @return  @RequestBody
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/eidt_company")
	@ResponseBody
	public ResultBooleanVO edit_company( MCompanyForm form) {
		if (StringUtils.isNotBlank(form.getEmail()) && !ValidateUtil.isEmailComOrCn(form.getEmail())) {
			log.info("邮箱格式错误email=",form.getEmail());
			return new ResultBooleanVO(false, null, "邮箱格式错误");
		}
		if (PaperType.IDENTITYCARD.equals(form.getPapers_type()) && !ValidateUtil.isLawNo(form.getPapers_num())) {
			log.info("身份证格式错误email=",form.getPapers_num());
			return new ResultBooleanVO(false, null, "身份证格式不正确");
		}

		if (null == form.getId()) {
			log.info("新增公司信息form={}",form);
			return mCompanyBizImpl.company_save(form, this.loginConsumer());
		} else {
			log.info("编辑公司信息form={}",form);
			ResultObjectVO<MCompanyVO> resultObjectVO = mBaseCompanyServiceImpl.search_by_bank_Ids(new MCompanyForm(form.getId()));
			MCompanyVO oldCompany = resultObjectVO.getObjVo();

			ResultBooleanVO result = mCompanyBizImpl.edit_company(form, this.loginConsumer());
			if (!result.isSuccess()) {
				return result;
			}
			resultObjectVO = mBaseCompanyServiceImpl.search_by_bank_Ids(form);
			MCompanyVO newCompany = resultObjectVO.getObjVo();

			return companyTypeChangeWebServiceImpl.companyTypeChange(oldCompany, newCompany, this.loginConsumer());
		}
	}

	/**
	 * 列表查询界面
	 * 
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/search_view_company")
	public ViewAndModel search_viewCompany() {
		ViewAndModel viewAndModel = new ViewAndModel(request, cache);
		viewAndModel.setViewName("company/commanage");
		return viewAndModel;
	}

	/**
	 * 获取公司分页数据
	 * 
	 * @param vo
	 * @param pageIndex
	 * @param pageCount
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/search_page_company")
	@ResponseBody
	public ResultListVO<MCompanyVO> search_Company(MCompanyForm form) {
		if ("".equals(form.getStatus())) {
			form.setStatus(null);
		}
		if (0 < form.getCreateDate().length()) {
			String[] data_str = form.getCreateDate().split("-");
			//form.setStart_time(data_str[0]);
			//form.setEnd_time(data_str[1]);
		}
		return companyWebServiceImpl.get_new_company_page(form);
	}

	/**
	 * 编辑界面
	 * 
	 * @param form
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/query_view_company/{id}")
	@ResponseBody
	public ViewAndModel query_view_company(MCompanyForm form) {
		return this.companyWebServiceImpl.query_view_company(this.createView(), form);
	}

	/**
	 * 编辑界面
	 * 
	 * @param form
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/query_company_by_id/{id}")
	@ResponseBody
	public ResultObjectVO<MCompanyVO> query_company_by_id(Long id) {
		log.debug("根据id查询公司信息id={}", id);
		return mBaseCompanyServiceImpl.search_by_bank_Ids(new MCompanyForm(id));
	}

	/**
	 * 公司管理-启用/停用
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/edit_status")
	@ResponseBody
	public ResultBooleanVO edit_status(HttpServletRequest request, HttpServletResponse response){
		Long id = Long.valueOf(request.getParameter("id"));
		String status = request.getParameter("status");
		log.debug("添加系统操作日志：MCompanyController===edit_status==id:" + id);
		log.debug("添加系统操作日志：MCompanyController===edit_status==status:" + status);
		if (0 == id) {
			return null;
		}
		if ("".equals(status)) {
			return null;
		}
		return mCompanyBizImpl.edit_status(id, status, this.loginConsumer());
	}

	/**
	 * 公司管理-下拉公司列表
	 * 
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/query_comman_branch")
	@ResponseBody
	public ResultDropDownListVO<MDropDownVO> ajax_company_info_(HttpServletRequest request) throws IOException {
		String str = request.getQueryString();
		String q = str.split("&")[0];
		MCompanyForm form = new MCompanyForm();
		if (null != q) {
			String company_name = new String(q.split("=")[1].getBytes("iso8859_1"));
			form.setCompany_name(java.net.URLDecoder.decode(company_name, "utf-8"));
		}

		return mBaseCompanyServiceImpl.query_company(form);
	}

	/**
	 * 公司管理-下拉查询渠道公司列表
	 * 
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/query_comman_channel")
	@ResponseBody
	public ResultDropDownListVO<MDropDownVO> ajax_company_info_channel(HttpServletRequest request) throws  IOException {
		String str = request.getQueryString();
		String q = str.split("&")[0];
		MCompanyForm form = new MCompanyForm();
		if (null != q) {
			String company_name = new String(q.split("=")[1].getBytes("iso8859_1"));
			form.setCompany_name(java.net.URLDecoder.decode(company_name, "utf-8"));
		}

		return mBaseCompanyServiceImpl.query_company_channel(form);
	}

	/**
	 * 公司管理-下拉查询渠道公司列表
	 * 
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/query_company_for_select")
	@ResponseBody
	public ResultDropDownListVO<MDropDownVO> query_company_for_select(HttpServletRequest request) throws  IOException {
		String str = request.getQueryString();
		String q = str.split("&")[0];
		MCompanyForm form = new MCompanyForm();
		if (null != q) {
			String company_name = new String(q.split("=")[1].getBytes("iso8859_1"));
			form.setCompany_name(java.net.URLDecoder.decode(company_name, "utf-8"));
		}

		return mBaseCompanyServiceImpl.query_list_for_select(form);
	}

	@RequestMapping("/query_comman_list")
	@ResponseBody
	public ResultListVO<MCompanyVO> getCompanyList(HttpServletRequest request, HttpServletResponse response) throws  IOException {
		String str = request.getQueryString();
		String q = str.split("&")[0];
		MCompanyForm form = new MCompanyForm();
		if (null != q) {
			String company_name = new String(q.split("=")[1].getBytes("iso8859_1"));
			form.setCompany_name(java.net.URLDecoder.decode(company_name, "utf-8"));
		}
		return mBaseCompanyServiceImpl.get_company_page(form);
	}
	
	/**
	 * 获取请求
	 * 
	 * @param req
	 * @return
	 * @throws IOException
	 */
	protected String extractParams(HttpServletRequest req) throws IOException {
		ByteArrayOutputStream output;
		InputStream is = req.getInputStream();
		output = new ByteArrayOutputStream();
		try {
			IOUtils.copy(is, output);
		} catch (Exception e) {
			log.error("请求超时 HttpServletRequest is error={}:" , e);
		} finally {
			is.close();
		}

		return output.toString("UTF-8");
	}

	/**
	 * 开户
	 * 
	 * @param comIds
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "openCompanyAccounts")
	@ResponseBody
	public ResultVerifyVO<MVerifOpenAccountVO> openCompanyAccounts(String comIds){
		if (StringUtil.isBlank(comIds)) {
			return null;
		}
		String[] comids = comIds.split(",");
		Long[] companyIds = new Long[comids.length];
		for (int i = 0; i < comids.length; i++) {
			companyIds[i] = Long.valueOf(comids[i]);
		}
		return companyWebServiceImpl.open_account_info(companyIds);
	}
	/**
	 * 子账户开户（华夏二代接口开户）
	 * 
	 * @param ids
	 * @return
	
	@RequestMapping(value = "openCompanyAccounts/huaxia02")
	@ResponseBody
	public ResultVerifyVO<MVerifOpenAccountVO> openConsumerAccountsHuaxia02(Long[] comIds) {
		log.debug(" MPersonConsumerInfoController   方法   openConsumerAccounts 调用");
		return companyWebServiceImpl.accountInfoHuaxia02(comIds);
	} */
	/** 后台-公司开通华夏交易会员代码**/
	@RequestMapping(value = "openCompanyAccounts/huaxia02")
	@ResponseBody
	public ResultVerifyVO<MVerifOpenAccountVO> companyAccountInfoHuaxia02(Long[] companyIds) {
		log.info("companyIds={}", NumberUtil.arrayToStr(companyIds));
		return companyWebServiceImpl.accountInfoHuaxia02(companyIds);
	}
	/**
	 * 跳转到渠道切换界面
	 */
	@RequestMapping(value = "openAccountView")
	public ViewAndModel openAccountView(Long companyId,String channelType) {
		log.debug(" 跳转到渠道切换界面");
		ViewAndModel model = new ViewAndModel(request, cache);
		companyWebServiceImpl.openAccountView(model, companyId, channelType);
		return model;
	}
	/** 公司切换使用的渠道类型 **/
	@RequestMapping(value = "changeTradeMemCode")
	@ResponseBody
	public ResultBooleanVO changeTradeMemCode(Long companyId,String relation_num ) {
		return companyWebServiceImpl.changeTradeMemCode(companyId, relation_num);
	}
	/** 公司录入新的银行卡信息 **/
	@RequestMapping(value = "insertBankNotDefault")
	@ResponseBody
	public ResultBooleanVO insertBankNotDefault(@RequestBody MConsumerBankMapForm bankMapForm) {
		return companyWebServiceImpl.insertBankNotDefault(bankMapForm, this.loginConsumer());
	}
	/**开通华夏子账号
	@RequestMapping(value = "openHx2AccountNo")
	@ResponseBody
	public ResultBooleanVO openHx2AccountNo(String tradeMemCode,Long bankMapId){
		log.debug(" 开通华夏子账号 bankMapId={}",bankMapId);
		return companyWebServiceImpl.openHx2AccountNo(tradeMemCode,bankMapId);
	}*/
	/**
	 * 绑定出入金卡界面跳转
	 * @param consumer_id
	 * @param bank_map_id
	 * @return
	 */
	@RequestMapping(value = "query_code/bindBankCardView/{company_id}")
	@ResponseBody
	public ViewAndModel bindBankCardView(@PathVariable Long company_id) {
		log.debug(" MPersonConsumerInfoController   方法   openConsumerAccounts 调用");
		return companyWebServiceImpl.bindBankCardView(this.createView(),company_id);
	}
	/**
	 * 绑定出入金卡数据获取
	 * @param consumer_id
	 * @param bank_map_id
	 * @return
	 */
	@RequestMapping(value = "query_code/bindBankCardList")
	@ResponseBody
	public ResultListVO<MConsumerBankMapVO> bindBankCardList( Long company_id) {
		log.debug(" MPersonConsumerInfoController   方法   openConsumerAccounts 调用");
		return companyWebServiceImpl.bindBankCardList(company_id);
	}
	/**
	 * 绑定出入金卡
	 * @param consumer_id
	 * @param bank_map_id
	 * @return
	 */
	@RequestMapping(value = "eidt_company/bindBankCard/{company_id}/{bank_map_id}")
	@ResponseBody
	public ResultBooleanVO bindBankCard(@PathVariable Long company_id,@PathVariable Long bank_map_id) {
		log.debug(" MPersonConsumerInfoController   方法   openConsumerAccounts 调用");
		return companyWebServiceImpl.bindBankCard(company_id,bank_map_id);
	}
	/**
	 * 解除出入金卡
	 * @param consumer_id
	 * @param bank_map_id
	 * @return
	 */
	@RequestMapping(value = "eidt_company/relieveBankCard/{company_id}")
	@ResponseBody
	public ResultBooleanVO relieveBankCard(@PathVariable Long company_id) {
		log.debug(" 解除出入金卡   方法   company_id={}",company_id);
		return companyWebServiceImpl.relieveBankCard(company_id);
	}
	/**
	 * 子账户信息变更
	 * @param consumer_id
	 * @return
	 */
	@RequestMapping(value = "eidt_company/accountInfoChange")
	@ResponseBody
	public ResultBooleanVO accountInfoChange(Long[] comIds){
		log.debug("子账户信息变更consumer_id={}",NumberUtil.arrayToStr(comIds));
		return companyWebServiceImpl.accountInfoChangeBatch(comIds);
	}
//	/**
//	 * 子账户信息查询
//	 * @param consumer_id
//	 * @return
//	 */
//	@RequestMapping(value = "eidt_company/getAccountInfo")
//	@ResponseBody
//	public B2BQueryAccountVO getAccountInfo(Long company_id){
//		log.debug("子账户信息变更consumer_id={}",company_id);
//		return companyWebServiceImpl.getAccountInfo(company_id);
//	}
}
